#include "eeprom.h"
#include <i2c.h>
#include "i2c_extras.h"
#include <sw_i2c.h>

void WriteLongEEPROM(unsigned long addr, unsigned long i) {
   WriteEEPROM(addr,   (i & 0x000000ff));
   WriteEEPROM(addr+1, (i & 0x0000ff00)>>8);
   WriteEEPROM(addr+2, (i & 0x00ff0000)>>16);
   WriteEEPROM(addr+3, (i & 0xff000000)>>24);
}

unsigned long ReadLongEEPROM(unsigned long addr) {
   unsigned char c[4];
   unsigned long b0, b1, b2, b3, i;
   ReadEEPROM(addr, c, 4);

   b0 = c[0]; b1 = c[1], b2=c[2], b3=c[3];
   i = b0 + (b1<<8) + (b2<<16) + (b3<<24);
   return i;
}

unsigned char ReadCharEEPROM(unsigned long addr) {
   unsigned char c[1];
   ReadEEPROM(addr, c, 1);
   return c[0];
}

/*
void WriteEEPROM(unsigned long addr, unsigned char data) {
    unsigned char ControlByte = 0xA0;       
    unsigned char HighAdd, LowAdd;

    if(addr>65535) ControlByte = ControlByte | 0x08; // block select for addresses over 512kbit

    HighAdd = (addr & 0x0000ff00) >> 8;
    LowAdd = addr & 0x000000ff;   

    //sprintf(lcd_msg, "E %lu %u %u", addr, HighAdd, LowAdd);    

    HDByteWriteI2C(ControlByte, HighAdd, LowAdd, data );
}

void ReadEEPROM(unsigned long addr, unsigned char *data, unsigned char length) {
    unsigned char ControlByte = 0xA0;       
    unsigned char HighAdd, LowAdd;

    if(addr>65535) ControlByte = ControlByte | 0x08; // block select for addresses over 512kbit

    HighAdd = (addr & 0x0000ff00) >> 8;
    LowAdd = addr & 0x000000ff;       

    HDByteReadI2C(ControlByte, HighAdd, LowAdd, data, length);
}
*/

void WriteEEPROM(unsigned long addr, unsigned char data) {
    unsigned char ControlByte = 0xA0;       
    unsigned char HighAdd, LowAdd;

    if(addr>65535) ControlByte = ControlByte | 0x08; // block select for addresses over 512kbit

    HighAdd = (addr & 0x0000ff00) >> 8;
    LowAdd = addr & 0x000000ff;   

    SWStartI2C();
    SWPutcI2C(ControlByte); // control byte
    SWAckI2C();
    SWPutcI2C(HighAdd); // word address
    SWAckI2C();
    SWPutcI2C(LowAdd); // word address
    SWAckI2C();
    SWPutcI2C(data); // data
    SWAckI2C();
    SWStopI2C();

    // HDByteWriteI2C(ControlByte, HighAdd, LowAdd, data );

}

void ReadEEPROM(unsigned long addr, unsigned char *data, unsigned char length) {
    unsigned char ControlByte = 0xA0;       
    unsigned char HighAdd, LowAdd;

    if(addr>65535) ControlByte = ControlByte | 0x08; // block select for addresses over 512kbit

    HighAdd = (addr & 0x0000ff00) >> 8;
    LowAdd = addr & 0x000000ff;       

    SWStartI2C();
    SWPutcI2C(ControlByte); // control byte
    SWAckI2C();
    SWPutcI2C(HighAdd); // word address
    SWAckI2C();
    SWPutcI2C(LowAdd); // word address
    SWAckI2C();
    SWRestartI2C();
    SWPutcI2C(ControlByte | 1); 
    SWAckI2C();
    SWGetsI2C(data, length);
    SWNotAckI2C();
    SWStopI2C();

    //HDByteReadI2C(ControlByte, HighAdd, LowAdd, data, length);
}
